package com.happypets.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.happypets.model.CartBean;
import com.happypets.model.PetBean;
import com.happypets.servicesImpl.PetServiceImpl;
import com.happypets.servicesImpl.UserServiceImpl;

public class CartAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserServiceImpl ser = new UserServiceImpl();
    public CartAjax() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-store"); 
		

		
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		
		
		String petId = request.getParameter("id");
		String count = request.getParameter("count");
		String flag = request.getParameter("flag");
		String userId= request.getParameter("userId");
		String price = request.getParameter("price");
		
		boolean boo = petId == null || count ==null || flag == null || userId == null || price == null ;
		
		if(boo){
			out.write("add error!");
			out.flush();
			out.close();
		}else{
			CartBean cart = new CartBean();
			
			cart.setUserId(userId);
			if(!flag.equals("0")){
				PetServiceImpl pt = new PetServiceImpl();
				PetBean p = pt.getPetBean(petId);
				
				cart.setName(p.getName());
				cart.setCount(Integer.parseInt(count));
				cart.setId(petId);
				cart.setPrice(Double.parseDouble(price));
				
				cart.setImage(p.getImage1());
			}
			
//			System.out.println("addCart:petId "+petId+" count "+count+" flag "+flag+" userId "+userId+" price "+price);
			List<Map<String,String>> lm = new LinkedList<Map<String,String>>();
			Map<String,String> ms = new HashMap<String,String>();
			
			System.out.println("购物车的flag ： "+flag);
			
			switch(Integer.parseInt(flag)){
				case 1:	
					if(add(cart, session)){
						ms.put("msg", "添加成功");
					}else{
						ms.put("msg", "添加失败");
					};				break;
				case 2:	if(remove(cart, session)){
					ms.put("msg", "删除成功");
				}else{
					ms.put("msg", "删除成功");
				};		break;
				case 3: lookCart(cart,session); break;
				case 0:	empty(cart,session);	 ms.put("msg", "清空成功");;				
				break;
			}
			if(Integer.parseInt(flag) != 0){
				ms.put("allCount", String.valueOf(inCartAllPetCount(session)));
				ms.put("allMoney", String.valueOf(inCartAllMoney(session)));
				
			}else{
				ms.put("allCount", "0");
				ms.put("allMoney","0");
				
			}
			lm.add(ms);
			
			Gson gson=new Gson();
			String json=gson.toJson(lm);
//			System.out.println(json);
			out.write(json);
			
			out.flush();
			out.close();
			
		}
		
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	/**
	 * 是否重复 
	 * @param petId
	 * @param session
	 * @return
	 */
	public boolean isDouble(String petId,HttpSession session){
		//先检查重复性
		List<CartBean> lc = (List<CartBean>) session.getAttribute("carts");
		if(lc == null){
			return false;
		}else{
			LinkedList<String> ls = new LinkedList<String>();
			for (int i = 0; i < lc.size(); i++) {
				ls.add(lc.get(i).getId());
			}
			return ls.contains(petId);
		}
	}
	
	
	public boolean add(CartBean cart,HttpSession session){
		
		int i =ser.addToCart(cart);
		
		session.setAttribute("carts", ser.findCart(cart.getUserId()));
		System.out.println("add cart "+i);
		return i==1;
	}
	
	public boolean remove(CartBean cart,HttpSession session){
		
		int i = ser.delFromCart(cart);
		
		session.setAttribute("carts", ser.findCart(cart.getUserId()));
		
		System.out.println("del cart "+i);
		return i == 1;
		}
	
	public void empty(CartBean cart , HttpSession session){
		
		ser.emptyCart(cart);
		
		session.removeAttribute("carts");
		
	}
	
	public void lookCart(CartBean cart , HttpSession session){
		session.setAttribute("carts", ser.findCart(cart.getUserId()));
	}
	
	
	public int inCartAllPetCount(HttpSession session){
		List<CartBean> lc = (List<CartBean>) session.getAttribute("carts");
		
		if(lc == null){
			return 0;
		}
		
		int all = 0;
		
		for (int i = 0; i < lc.size(); i++) {
			CartBean cb = lc.get(i);
			all += cb.getCount();
			
		}
		return all;
	}
	
	public double inCartAllMoney(HttpSession session){
		List<CartBean> lc = (List<CartBean>) session.getAttribute("carts");
		
		if(lc == null){
			return 0;
		}
		
		double all = 0;
		
		for (int i = 0; i < lc.size(); i++) {
			CartBean cb = lc.get(i);
			all += cb.getPrice()*cb.getCount();
		}
		
		return all;
	}
	

}
